package fudan.se.project.config;

import fudan.se.project.domain.User;
import fudan.se.project.domain.sysrole.SystemAuthority;
import fudan.se.project.repository.entity.conference.ConferenceRepository;
import fudan.se.project.service.infrastructure.entity.UserService;
import fudan.se.project.service.infrastructure.entity.conference.ConferenceService;
import fudan.se.project.service.infrastructure.entity.sysrole.SystemAuthorityService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Collections;
import java.util.HashSet;

import static fudan.se.project.domain.sysrole.SystemAuthority.Authority.ADMIN;
import static fudan.se.project.domain.sysrole.SystemAuthority.Authority.USER;

@Configuration
public class DatabaseConfig {
    @Bean
    public PasswordEncoder encoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public CommandLineRunner dataLoader(
            PasswordEncoder encoder,
            UserService userService,
            ConferenceService conferenceService,
            SystemAuthorityService systemAuthorityService,
            ConferenceRepository conferenceRepository
    ) {
        return args -> {

            systemAuthorityService.getSystemAuthority(USER);
            final SystemAuthority authAdmin = systemAuthorityService.getSystemAuthority(ADMIN);


            User admin = new User(
                    "admin",
                    null,
                    encoder().encode("password"),
                    null,
                    null,
                    null
            );

            admin.setSystemAuthorities(new HashSet<>(Collections.singletonList(authAdmin)));
            userService.save(admin);


        };
    }
}
